public class HashBucket {
    private static class Node {
        private int key;
        private int value;
        Node next;

        public Node(int key, int value) {
            this.key = key;
            this.value = value;
        }
    }

    private Node[] array;
    private int size; // 当前的数据个数
    private static final double LOAD_FACTOR = 0.75;
    private static final int DEFAULT_SIZE = 8; // 默认桶的大小

    public int put(int key, int value) {
        // 计算哈希桶下标
        int index = key % array.length;

        // 在当前链表查找key是否已存在，如果存在则更新value
        for (Node cur = array[index]; cur != null; cur = cur.next) {
            if (cur.key == key) {
                int oldValue = cur.value;
                cur.value = value;
                return oldValue;
            }
        }

        // 插入新节点
        Node newNode = new Node(key, value);
        newNode.next = array[index];
        array[index] = newNode;
        size++;

        // 判断是否需要进行扩容
        if (loadFactor() >= LOAD_FACTOR) {
            resize();
        }

        return -1;
    }

    private void resize() {
        int newSize = array.length * 2;
        Node[] newArray = new Node[newSize];

        // 将原哈希桶中的元素重新哈希到新的桶中
        for (int i = 0; i < array.length; i++) {
            Node cur = array[i];
            while (cur != null) {
                Node next = cur.next;
                int newIndex = cur.key % newSize;
                cur.next = newArray[newIndex];
                newArray[newIndex] = cur;
                cur = next;
            }
        }

        array = newArray;
    }

    private double loadFactor() {
        return size * 1.0 / array.length;
    }

    public HashBucket() {
        array = new Node[DEFAULT_SIZE];
        size = 0;
    }

    public int get(int key) {
        int index = key % array.length;

        for (Node cur = array[index]; cur != null; cur = cur.next) {
            if (cur.key == key) {
                return cur.value;
            }
        }

        return -1; // 未找到对应的key
    }
}